import { Component } from '@angular/core';
import { NavController, LoadingController, ToastController, Events, AlertController } from 'ionic-angular';
// import { Storage } from "@ionic/storage";
import { BaseUI } from '../../common/baseui';
import { ApiProvider } from '../../providers/api/api';
// import { InAppBrowser } from '@ionic-native/in-app-browser';
import { ThemeableBrowser, ThemeableBrowserOptions, ThemeableBrowserObject } from '@ionic-native/themeable-browser';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { Device } from '@ionic-native/device';
// @IonicPage()
@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class ContactPage extends BaseUI{
  productArr: any[];
  errorMessage: any;
  private options: ThemeableBrowserOptions = {
    statusbar: {
      color: '#5695DCff'
    },
    toolbar: {
        height: 44,
        color: '#5695DCff'
    },
    title: {
        color: '#FFFFFFff',
        showPageTitle: true
    },
    closeButton: {
      wwwImage: 'assets/imgs/back.png',
      align: 'left',
      event: 'closePressed',
      wwwImageDensity: 1.7
    },
    backButtonCanClose: true
  };
  browser:ThemeableBrowserObject;
  constructor(public navCtrl: NavController,
              // public storage: Storage,
              public api: ApiProvider,
              public loadingCtrl: LoadingController,
              // public iab: InAppBrowser,
              private themeableBrowser: ThemeableBrowser,
              public toastCtrl: ToastController,
              public events: Events,
              private alertCtrl: AlertController,
              private transfer: FileTransfer,
              private file: File,
              private fileOpener: FileOpener,
              private androidPermissions: AndroidPermissions,
              private device: Device
              ) {
    super();
  }
  getlastXieGang(str){
    let string = str;
    var index = string.lastIndexOf("\/");  
    string = string.substring(index + 1, string.length);
    return string;
  }
  downloadApp(apkUrl, browser) {
    browser.close();
    let alert = this.alertCtrl.create({
        title: '下载进度：0%',
        enableBackdropDismiss: false,
        buttons: ['后台下载']
    }); 
    alert.present();
    
    const fileTransfer: FileTransferObject = this.transfer.create();
    const apk = this.file.externalRootDirectory + this.getlastXieGang(apkUrl); //apk保存的目录
    fileTransfer.download(apkUrl, apk).then(() => {
        this.fileOpener.open(apk, 'application/vnd.android.package-archive').then(() =>{
            console.log('File is opened')
        }).catch(e => {
            console.log('Error openening file', e)
        });
    });
    fileTransfer.onProgress((event: ProgressEvent) => {
        let num = Math.floor(event.loaded / event.total * 100);
        if (num === 100) {
            alert.dismiss();
        } else {
            let title = document.getElementsByClassName('alert-title')[0];
            title && (title.innerHTML = '正在为您下载……');
        }
    });
  }
  userDate(url, browser){
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(
      result => {
        console.log('Has permission?', result.hasPermission)
        // this.downloadApp(url, browser)
      },
      err => {
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
      }
    );
    return new Promise((resolve)=>{
      this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE, this.androidPermissions.PERMISSION.GET_ACCOUNTS]).then((res)=>{
        this.downloadApp(url, browser)
        resolve(res)
      })
    })
  }
  itemSelected(item){
    this.api.getProductUrlById({productId: item.productId }).subscribe(f => {
        
      // 判断链接是否有协议，没有则加上
      if(f!=null && f['result'].indexOf('https://') === -1 && f['result'].indexOf('http://') === -1){
        item.productShortUrl = 'http://' + f['result']
      }else{
        item.productShortUrl =  f['result']
      }
      let params = {
        phoneNum: window.localStorage.getItem('phoneNum'),   //用户id
        event: 'APP_PPV',
        extraParam1: item.productId,//点击app的id
        extraParam2: '必下款'
      };
      this.options['title']['staticText'] = item.productName;
      this.api.addEvent(params).subscribe(g => {
        console.log('APP点击埋点触发');
      }, err => {
        if(err == 401 || err == 500){
          window.localStorage.removeItem('phoneNum')
          this.events.publish('toLogin');
        }
      });
      this.browser = this.themeableBrowser.create(item.productShortUrl, '_blank', this.options);
      let t;
      let data = {
        phoneNum: window.localStorage.getItem('phoneNum'),   //用户id
        event: 'APP_PPR',
        extraParam1: item.productId,//点击app的id
        extraParam2: '必下款'
      }
      t = setTimeout(() => {
        this.api.addEvent(data).subscribe(h => {
          console.log('预计注册埋点触发');
        })
      }, 15000)
      this.browser.on('loadstart').subscribe(event => {
        if (event['url'].indexOf('.apk') > -1){
          if((this.device.model.toLowerCase().indexOf('oppo') > -1) || (this.device.model.toLowerCase().indexOf('vivo') > -1)){
            this.browser = this.themeableBrowser.create(event['url'], '_system', this.options);
          }else{
            this.userDate(event['url'], this.browser)
          }
        }
      });
      this.browser.on('exit').subscribe(event => {
        clearTimeout(t);
        console.log('预计注册埋点取消');
      });
    }, err => {
      this.errorMessage=<any>err 
    })


  }
  getData(){
    let loading = super.showLoading(this.loadingCtrl, "");
    this.productArr = [];
    this.api.getBxkList({pageNum: 1,pageSize: 10,mustSwitch:1}).subscribe(f => {
      this.productArr = f['list']
      console.info("bixiakuan:"+f )
      loading.dismiss()
    }, err => {
      this.errorMessage=<any>err;
      loading.dismiss()
      if(err == 401 || err == 500){
        window.localStorage.removeItem('phoneNum')
        this.events.publish('toLogin');
      }
    })
  }
  // 必下款列表埋点
  activeEvent(){
    let params = {
      'event': 'APP_MPV',
      'phoneNum': window.localStorage.getItem('phoneNum')
    }
    this.api.addEvent(params).subscribe(g => {
      console.log('必下款列表埋点触发', g);
    }, err => {
      if(err == 401 || err == 500){
        window.localStorage.removeItem('phoneNum')
        this.events.publish('toLogin');
      }
    })
  }
  ionViewDidLoad(){
    this.getData();
    this.activeEvent();
  }
  //下拉刷新
  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    setTimeout(() => {
      this.getData();  //绑定方法
      console.log('Async operation has ended');
      refresher.complete();
    }, 1000);
  }
  // 进入页面之前
  ionViewDidEnter(){
    this.getData()
  }
}
